﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;

namespace XieCan.AspMVC.Extensions
{
    /// <summary>
    /// NameValueCollection扩展类
    /// </summary>
    public static class NameValueCollectionEx
    {
        /// <summary>
        /// 将NameValueCollection转化为Dictionary<string, object>
        /// </summary>
        /// <param name="NameValues"></param>
        /// <param name="Multiple">是否存在一个键多个值?</param>
        /// <returns></returns>
        public static OperateResult<Dictionary<string, object>> ToDictionary(this NameValueCollection NameValues, bool Multiple = false)
        {
            try
            {
                var result = new Dictionary<string, object>();
                foreach (string key in NameValues.Keys)
                {
                    if (Multiple)
                    {
                        string[] values = NameValues.GetValues(key);
                        if (values.Length == 1)
                        {
                            result.Add(key, values[0]);
                        }
                        else
                        {
                            result.Add(key, values);
                        }
                    }
                    else
                    {
                        result.Add(key, NameValues[key]);
                    }
                }

                return OperateResult<Dictionary<string, object>>.Succeeded(result);

            }
            catch (Exception ex)
            {
                return OperateResult<Dictionary<string, object>>.Failed(ex);
            }
        }

        /// <summary>
        /// 将NameValueCollection序列化为JSON字符串
        /// </summary>
        /// <param name="NameValues"></param>
        /// <param name="Multiple">是否存在一个键多个值?</param>
        /// <returns></returns>
        public static OperateResult<string> ToJson(this NameValueCollection NameValues, bool Multiple = false)
        {
            var result = NameValues.ToDictionary(Multiple);
            if (result.Success)
            {
                return result.Data.ToJson();
            }
            return OperateResult<string>.Failed(result.Error);
        }
    }
}
